import numpy as np
import os
import paddle
import paddle.nn.functional as F
from paddle.nn import Linear

def load_data():
    data_file = './data/housing.data'
    data = np.fromfile(data_file, sep=' ', dtype=np.float32)

    # 每条数据包括14项，其中前面13项是影响因素，第14项是相应的房屋价格中位数
    feature_names = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', \
                     'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV']
    feature_num = len(feature_names)

    # 将原始数据进行Reshape，变成[N, 14]这样的形状
    data = data.reshape([data.shape[0] // feature_num, feature_num])

    # 将原数据集拆分成训练集和测试集
    # 这里使用80%的数据做训练，20%的数据做测试
    # 测试集和训练集必须是没有交集的
    ratio = 0.8
    offset = int(data.shape[0] * ratio)
    training_data = data[:offset]

    """ 归一化处理 """
    # 计算train数据集的最大值，最小值
    maximums, minimums = training_data.max(axis=0), training_data.min(axis=0)

    # 记录数据的归一化参数，在预测时对数据做归一化
    global max_values
    global min_values

    max_values = maximums
    min_values = minimums

    # 对数据进行归一化处理
    for i in range(feature_num):
        data[:, i] = (data[:, i] - min_values[i]) / (max_values[i] - min_values[i])

    # 训练集和测试集的划分
    training_data = data[:offset]
    test_data = data[offset:]
    return training_data, test_data

class RegressionModel(paddle.nn.Layer):
    def __init__(self):
        super(RegressionModel, self).__init__()
        # 增加隐藏层以提高模型表达能力
        self.fc1 = Linear(13, 64)
        self.fc2 = Linear(64, 32)
        self.fc3 = Linear(32, 1)

    def forward(self, inputs):
        # 添加激活函数以增加非线性
        y_predict = self.fc1(inputs)
        y_predict = F.relu(y_predict)
        y_predict = self.fc2(y_predict)
        y_predict = F.relu(y_predict)
        y_predict = self.fc3(y_predict)
        return y_predict


def createModel():
    model = RegressionModel()
    model.train()

    training_data, test_data = load_data()

    # 进一步降低学习率并增加训练轮数
    opts = paddle.optimizer.Adam(learning_rate=0.001, parameters=model.parameters())

    EPCOH = 100  # 增加训练轮数到100轮
    BATCH_SIZE = 10

    for epoch in range(EPCOH):
        np.random.shuffle(training_data)
        mini_batches = [training_data[k:k+BATCH_SIZE] for k in range(0, len(training_data), BATCH_SIZE)]
        for iter_id,mini_batches in enumerate(mini_batches):
            x = np.array(mini_batches[:, :-1])
            y = np.array(mini_batches[:, -1:])
            house_features = paddle.to_tensor(x)
            price = paddle.to_tensor(y)

            predicts = model(house_features)

            Loss = F.square_error_cost(predicts, label=price)
            avg_loss = paddle.mean(Loss)
            if iter_id % 20 == 0:
                print("epoch: {}, batch_id: {}, loss is: {}".format(epoch, iter_id, avg_loss.numpy()))

            avg_loss.backward()
            opts.step()
            opts.clear_grad()

    paddle.save(model.state_dict(), 'LR_model.pdparams')
    print("模型保存成功，模型参数保存在LR_model.pdparams中")

def predict_one_example():
    training_data, test_data = load_data()
    idx = np.random.randint(0, test_data.shape[0])
    # 修复索引问题，使用随机索引而不是固定为-10
    one_data,label = test_data[idx, :-1], test_data[idx, -1:]
    print("数据: {}, 标签: {}".format(one_data, label))
    # 修复reshape问题，将结果赋值回去
    one_data = one_data.reshape([1, -1])

    model = RegressionModel()
    model_dict = paddle.load("LR_model.pdparams")
    model.load_dict(model_dict)
    model.eval()
    one_data = paddle.to_tensor(one_data)
    predict = model(one_data)
    predict = predict * (max_values[-1] - min_values[-1]) + min_values[-1]
    # 对label数据做反归一化处理
    label = label * (max_values[-1] - min_values[-1]) + min_values[-1]
    #print("预测结果：", predict.numpy()[0][0])
    #print("真实结果：", label[0][0])
    print("The predict result is {}, the corresponding label is {}".format(predict.numpy(), label))

if __name__ == '__main__':
    while True:
        print("1、建立模型")
        print("2、模型测试")
        print("0、退出")
        print("请输入选择：")
        choice = input()
        if choice == "1":
            createModel()
        elif choice=='2':
            predict_one_example()
        elif choice=='0':
            exit(0)
        else:
            print("输入错误")